import { create } from "zustand";
import { devtools } from "zustand/middleware";
import emitter from "../utils/events";
const useWebSocketStore = create(
  devtools((set, get) => ({
    socket: null,
    isConnected: false,
    messages: [],
    connect: () => {
      // 先检查是否已存在一个连接，如果存在，先关闭它
      const currentSocket = get().socket;
      if (currentSocket) {
        currentSocket.onclose = () => {
          // 只有在确认 WebSocket 完全关闭后，才创建新的实例
          createNewWebSocket();
        };
        currentSocket.close();
      } else {
        createNewWebSocket();
      }
      function createNewWebSocket() {
        const ws = new WebSocket("ws://127.0.0.1:3000");
        ws.onopen = () => {
          console.log("Connected to WS");
          set({ isConnected: true });
        };
        ws.onmessage = (event) => {
          const message = event.data;
          set((state) => ({ messages: [...state.messages, message] }));
          // 处理特定类型的消息
          handleMessages(message);
        };
        ws.onclose = () => {
          console.log("Disconnected from WS");
          set({ isConnected: false });
        };
        ws.onerror = (error) => {
          console.error("WebSocket Error:", error);
          set({ isConnected: false });
        };

        set({ socket: ws });
      }
    },
    disconnect: () => {
      if (get().socket) {
        get().socket.close();
      }
      set({ socket: null, isConnected: false });
    },
    sendMessage: (message) => {
      if (get().socket) {
        get().socket.send(message);
      }
    },
  }))
);

function handleMessages(message) {
  // 根据消息类型进行逻辑处理
  switch (message) {
    case "connection_success":
      emitter.emit("connection_success");
      break;
    case "login_success":
      emitter.emit("login_success");
      break;
    case "logout_success":
      emitter.emit("login_success");
      break;
    // 更多消息类型处理
    default:
      break;
  }
}

export default useWebSocketStore;
